import os,sys
import requests
import ssl
import urllib3
import random

urllib3.disable_warnings()
ssl._create_default_https_context = ssl._create_unverified_context
agents = [
		"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ????/1.0.0 Chrome/102.0.5005.167 Electron/19.1.8 Safari/{}.36".format(random.randint(1, 580)),
		"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ifonts_client/2.4.4 Chrome/87.0.4280.141 Electron/11.5.0 Safari{}.36".format(random.randint(1, 580)),
		"maxthon/6.2.0.1000 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/{}.36".format(random.randint(1, 580)),
		"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/{}.0".format(random.randint(1, 113))
	]

myHeaders = {"User-Agent":random.choice(agents)}

author = "李贞贤"

def getSongs():
	art_url = "https://music-api.tonzhon.com/songs_of_artist/{}".format(author)
	search_url = "https://music-api.tonzhon.com/search/n/{}".format(author)
	res = requests.get(search_url,headers = myHeaders,verify = False)
	if res.status_code != 200:
		print("歌曲列表获取失败")
		return

	song_dict = res.json().get("data")
	if song_dict == None:
		song_dict = res.json().get("songs")
	else:
		song_dict = song_dict.get("songs")

	for i in song_dict:
		SongFiles(song = i)

def CheckFolder(name):
	if not os.path.exists(name):
		os.makedirs(name)


def SongFiles(song = ""):
	if song == "":
		return
	api_url = "https://music-api.tonzhon.com/song_file/{}".format(song.get("newId"))
	songData = requests.get(api_url,headers = myHeaders,verify = False)
	if songData.json().get("success") == False:
		return
	song_url = songData.json().get("data")

	if "http" not in songData.json().get("data"):
		song_url = "https:{}".format(songData.json().get("data")) 

	
	res = requests.get(song_url,headers = myHeaders,verify = False)
	music_path = "H:/music/{}/".format(author)
	CheckFolder(music_path)
	song_name = "{}/{}.mp3".format(music_path,song.get("name").replace("/",""))
	if os.path.exists(song_name):
		song_name = "{}/{}_new.mp3".format(music_path,song.get("name").replace("/",""))
	with open(song_name, 'wb') as mp3_content:
		mp3_content.write(res.content)


if __name__ == '__main__':
	getSongs()